'use strict';

//导入模板引擎模块
let nunjucks = require('nunjucks');

//创建nunjucks的env实例
function createEnv(path,opts){
    path = path || 'views'
    opts = opts || {}
    let optionsEnv = {
        autoescape:opts.autoescape===undefined?true:opts.autoescape,      //自动转义，默认为true
        watch:opts.watch === undefined?false:opts.watch,                   //是否重新加载，默认为flase
        noCache:opts.noCache === undefined?false:opts.noCache,            //没有缓存时是否缓存，默认为flase
        throwOnUndefined:opts.throwOnUndefined === undefined?false:opts.throwOnUndefined     //抛出异常，默认为flase
    }
    //配置
    let env = nunjucks.configure(path,optionsEnv);
    //返回env
    return env;
}

//作为中间件暴露出去，必须为函数
module.exports = async (ctx,next) =>{
    //为ctx绑定render方法
    ctx.render = function(view,model){
        //调用方法
        let env = createEnv('views',{autoescape:false,watch:true,noCache:true})
        //渲染网页
        ctx.body = env.render(view,model);
    }
    //调用下一个异步函数
    await next();
}